﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace TSNPro.Base
{
    public class BaseFactory
    {
        private Dictionary<string, Type> _map;
        private static Type[] _allTypes;

        public BaseFactory()
        {
            _map = new Dictionary<string, Type>();
            _allTypes = Assembly.GetExecutingAssembly().GetTypes();
            // 假设我们已经将类型和类型名称映射到字典中
            // 例如：_map.Add("ConcreteType", typeof(ConcreteType));
        }

        
        public BaseItem CreateInstance(string concreteType)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            // 按类名结尾匹配筛选类型
            var matchingType = _allTypes.FirstOrDefault(t => t.Name.EndsWith(concreteType));
            // 如果没有找到匹配的类
            if (matchingType == null)
            {
                Console.WriteLine($"No class found ending with '{concreteType}'.");
                return null;
            }

            // 创建类型的实例
            BaseItem ret = Activator.CreateInstance(matchingType) as BaseItem;
            Console.WriteLine($"CreateInstance:{sw.ElapsedMilliseconds}ms");
            return ret;
        }

        public List<string> GetRegisterTypes()
        {
            return new List<string>(_map.Keys);
        }

        // 注册类型的方法
        public void RegisterType(string typeName, Type type)
        {
            if (!_map.ContainsKey(typeName))
            {
                _map.Add(typeName, type);
            }
        }
    }
}
